<?php
if (!defined('IN_IPB')) exit("<h1>Incorrect access</h1> You may not access this file without the acp.");

class lottery extends template_plugin
{
	var $ipsclass;
	
	var $name = "Lottery";
	var $multiple = 0;
	var $cache_array = array(
								'ibm_lottery' => array('Lottery cache','lottery_cache'),
							 );
	
	var $settings = array();
	var $odds = array();
	var $types = array();
	
	function lottery_cache()
	{
		$this->ipsclass->cache['ibm_lottery'] = array();
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_lottery','where'=>"l_status != 'drawn'"));
		$this->ipsclass->DB->exec_query();
		while($lottery = $this->ipsclass->DB->fetch_row())
		{
			$lottery['prizes'] = unserialize($lottery['prizes']);
			$this->ipsclass->cache['ibm_lottery'][$lottery['l_id']] = $lottery;
		}
		
		$this->ipsclass->update_cache( array( 'name' => 'ibm_lottery', 'array' => 1, 'deletefirst' => 1 ) );
	}
	
	function acp_menu()
	{
		return array(
					  1 => array('Current Lotteries','code=plugin&do=run&link='.$this->plugin['link']),
					  2 => array('Previous Lotteries','code=plugin&do=run&link='.$this->plugin['link'].'&action=previous'),
					);
	}
	
	function _load(&$plugin)
	{
		parent::_load($plugin);
		
		if($plugin['link'])
		{
			$this->settings = unserialize($plugin['plugin_config']);
		}
		else
		{
			$this->settings['send_pm'] = 1;
			$this->settings['win_subject'] = "You have just won the lottery";
			$this->settings['win_message'] = 
<<<EOF
{member_name},

You have just won the lottery, [url={base_url}index.php?autocom=market&plugin={plugin}&do=prize&lottery={lottery_id}]{lottery_name}[/url]

[b]This is an automated message[/b]
EOF;
		}
		
		require_once(ROOT_PATH."sources/market/lottery/lottery.php");
		
		if(!is_array($this->ipsclass->cache['ibm_lottery']))
		{
			$this->ipsclass->cache['ibm_lottery'] = array();
		}
		
		$time = time();
		if(IPB_THIS_SCRIPT == 'public' && $this->ipsclass->input['request_method'] != 'post')
		{
			foreach($this->ipsclass->cache['ibm_lottery'] as $id => $lottery)
			{
				if($lottery['end_time'] <= $time)
				{
					require_once(ROOT_PATH."sources/market/lottery/".$lottery['l_type']);
					$class = $this->ipsclass->market_class->get_class_name($lottery['l_type']);
					$type = new $class;
					$type->ipsclass =& $this->ipsclass;
					$type->_load($this->ipsclass->cache['ibm_lottery'][$id]);
					$numbers = $type->create_numbers();
					$correct = array();
					foreach($numbers as $i => $nums)
					{
						$keys = array_rand($nums['numbers'],$nums['max_pick']);
						if(!is_array($keys))
						{
							$keys = array($keys);
						}
						foreach($keys as $k)
						{
							$correct[$i][$k] = $nums['numbers'][$k];
						}
					}
					$tickets = 0;
					$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_lottery_tickets','where'=>"lottery_id=".$id));
					$q = $this->ipsclass->DB->exec_query();
					while($ticket = $this->ipsclass->DB->fetch_row($q))
					{
						$tickets++;
						$won = $type->check_ticket($ticket,$correct);
						$this->ipsclass->DB->do_update('market_lottery_tickets',array(
																						'checked' => 1,
																						't_correct' => $won === false ? '' : $won,
														),"t_id=".$ticket['t_id']);
						if($won)
						{
							$prize = 0;
							if($lottery['prizes']['money'][$won])
							{
								$prize = 1;
								$this->ipsclass->DB->build_and_exec_query(array('update'=>'members','set'=>$this->ipsclass->vars['market_members_field']."=".$this->ipsclass->vars['market_members_field']."+".$lottery['prizes']['money'][$won],'where'=>"id=".$ticket['member_id']));
								
								$this->ipsclass->market_class->record_reward($lottery['prizes']['money'][$won],$lottery['end_time']);
							}
							if($lottery['prizes']['items'][$won])
							{
								$prize = 1;
								foreach($lottery['prizes']['items'][$won] as $item_id => $quanity)
								{
									$expired = $this->ipsclass->cache['market_items'][$item_id]['expire_time'] > 0 ? $time + $this->ipsclass->cache['market_items'][$item_id]['expire_time'] * $this->ipsclass->cache['market_items'][$item_id]['expire_unit'] : 0;
									for($i = 0; $i < $quanity; $i++)
									{
										$inv_item = array(
															'member_id' => $ticket['member_id'],
															'item' => $item_id,
															'price_bought' => $this->ipsclass->cache['market_items'][$item_id]['price'],
															'resell_price' => $this->ipsclass->cache['market_items'][$item_id]['resell'],
															'time_bought' => $time,
															'settings' => '',
															'expired' => $expired,
														);
										if($this->ipsclass->market_class->items_loaded[$item_id]->public_on_create_item($inv_item))
										{
											$this->ipsclass->DB->do_insert('market_inventory',$inv_item);
										}
									}
								}
							}
							if($prize && $this->settings['send_pm'])
							{
								$subject = $this->settings['win_subject'];
								$message = $this->settings['win_message'];
								
								$member = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'members','where'=>"id=".$ticket['member_id']));
								$message = str_replace("{member_name}",$member['members_display_name'],$message);
								$message = str_replace("{base_url}",$this->ipsclass->base_url,$message);
								$message = str_replace("{plugin}",$this->plugin['link'],$message);
								$message = str_replace("{lottery_name}",$lottery['l_name'],$message);
								
								if($this->settings['send_pm'] == 1)
								{
									require_once( ROOT_PATH.'sources/lib/func_msg.php' );
							 		
									$msg_lib           =  new func_msg();
									$msg_lib->ipsclass =& $this->ipsclass;
									$msg_lib->init();
									
									$msg_lib->to_by_id    = $member['id'];
									$msg_lib->from_member = $member;
									$msg_lib->msg_title   = $subject;
									$msg_lib->msg_post    = $this->ipsclass->parser->pre_display_parse( $this->ipsclass->parser->pre_db_parse( $message ) );
									$msg_lib->force_pm    = 1;
									
									$msg_lib->send_pm();
								}
								else
								{
									require_once( ROOT_PATH."sources/classes/class_email.php" );
									
									$email           =  new emailer();
									$email->ipsclass =& $this->ipsclass;
									$email->email_init();
									
									$email->subject = $subject;
									$email->message = $this->ipsclass->parser->pre_display_parse( $this->ipsclass->parser->pre_db_parse( $message ) );
									$email->to      = $member['email'];
							
									$email->send_mail();
								}
							}
						}
					}
					
					$this->ipsclass->DB->do_update('market_lottery',array(
																			'l_status' => 'drawn',
																			'correct_numbers' => serialize($correct),
													),"l_id=".$id);
					
					if($lottery['continuous'])
					{
						$new_lottery = $lottery;
						
						$diff = $lottery['end_time'] - $lottery['start_time'];
						$diff2 = $lottery['start_time'] - $lottery['create_time'];
						if($new_lottery['continuous'] == 1)
						{
							$new_lottery['create_time'] = $lottery['end_time'] - $diff2;
							$new_lottery['start_time'] = $lottery['end_time'];
						}
						else
						{
							$new_lottery['create_time'] = $lottery['end_time'];
							$new_lottery['start_time'] = $new_lottery['create_time'] + $diff2;
						}
						$new_lottery['end_time'] = $new_lottery['start_time'] + $diff;
						
						if($new_lottery['stock_tickets'] >= 0)
						{
							$new_lottery['stock_tickets'] += $tickets;
						}
						
						$new_lottery['prizes'] = serialize($new_lottery['prizes']);
						unset($new_lottery['l_id']);
						$this->ipsclass->DB->do_insert('market_lottery',$new_lottery);
					}
					
					$this->lottery_cache();
					break;
				}
			}
		}
		
		foreach($this->ipsclass->cache['ibm_lottery'] as $i => $lottery)
		{
			if($lottery['start_time'] > $time && IPB_THIS_SCRIPT == 'public')
			{
				$this->ipsclass->cache['ibm_lottery'][$i]['l_status'] = 'closed';
			}
			require_once(ROOT_PATH."sources/market/lottery/".$lottery['l_type']);
			$class = $this->ipsclass->market_class->get_class_name($lottery['l_type']);
			$this->types[$lottery['l_id']] = new $class;
			$this->types[$lottery['l_id']]->ipsclass =& $this->ipsclass;
			$this->types[$lottery['l_id']]->_load($this->ipsclass->cache['ibm_lottery'][$i]);
		}
	}
	
	function acp_settings()
	{
		$this->ipsclass->parser->parse_smilies   = 1;
		$this->ipsclass->parser->parse_html      = 1;
		$this->ipsclass->parser->parse_bbcode    = 1;
		
		if ( $this->ipsclass->han_editor->method == 'rte' )
		{
			$message = $this->ipsclass->parser->pre_display_parse( $this->ipsclass->parser->pre_db_parse( $this->settings['win_message'] ) );
			$message = $this->ipsclass->parser->convert_ipb_html_to_html( $message );
		}
		else
		{
			$message = $this->ipsclass->parser->pre_edit_parse( $this->settings['win_message'] );
		}
		
		$html = "";
		
		$html .= $this->ipsclass->adskin->add_td_row(array(
															"<b>Send a Message?",
															$this->ipsclass->adskin->form_dropdown('send_pm',array(array(0,'Do not send a message'),array(1,'Send a PM'),array(2,'Send an email')),$this->settings['send_pm']),
													)	);
		
		$html .= $this->ipsclass->adskin->add_td_row(array(
															"<b>General Subject:</b>",
															$this->ipsclass->adskin->form_input('win_subject',$this->settings['win_subject']),
													)	);
		
		$html .= $this->ipsclass->adskin->add_td_row(array(
															"<b>General Message:</b><br />Tags:<br />{member_name} = Member Name of Winner<br />{base_url} = Base URL for the board<br />{plugin} = The plugin link/id for this lottery plugin<br />{lottery_id} = The ID of the lottery<br />{lottery_name} = The name of the lottery",
															$this->ipsclass->han_editor->show_editor( $message, 'win_message' ),
													)	);
		
		return $html;
	}
	
	function acp_save_settings(&$input)
	{
		$this->ipsclass->parser->parse_smilies   = 1;
		$this->ipsclass->parser->parse_html      = 1;
		$this->ipsclass->parser->parse_bbcode    = 1;
		
		$save = array();
		$save['send_pm'] = min(max(intval($this->ipsclass->input['send_pm']),0),2);
		$save['win_subject'] = $this->ipsclass->input['win_subject'];
        $save['win_message'] = $this->ipsclass->han_editor->process_raw_post( 'win_message' );
		$save['win_message'] = $this->ipsclass->parser->pre_edit_parse( $this->ipsclass->parser->pre_db_parse( $save['win_message'] ) );
		
		$input['plugin_config'] = serialize($save);
	}
	
	function acp()
	{
		// Yes redirect again >_>
		$redirect = array(
								'list' => 'list_lottery',
								'edit' => 'edit_lottery',
								'type' => 'type_lottery',
								'form' => 'form_lottery',
								'save' => 'save_lottery',
								'delete' => 'delete_lottery',
								'tickets' => 'view_tickets',
								'previous' => 'old_lottery',
								'result' => 'view_result',
							);
		if(!$redirect[$this->ipsclass->input['action']])
		{
			$this->ipsclass->input['action'] = 'list';
		}
		
		$function = 'acp_'.$redirect[$this->ipsclass->input['action']];
		$this->$function();
	}
	
	function acp_list_lottery()
	{
		$trans = array();
		$trans['open'] = "Open";
		$trans['closed'] = "Closed";
		
		$this->ipsclass->admin->nav[] 		 = array( $this->ipsclass->form_code.'&amp;action=list', 'Manage Lotteries' );
		
		$this->ipsclass->adskin->td_header[] = array( "Name/Description"             , "" );
		$this->ipsclass->adskin->td_header[] = array( "Status/Tickets Available"     , "" );
		$this->ipsclass->adskin->td_header[] = array( "Time Starting/Ending"         , "" );
		$this->ipsclass->adskin->td_header[] = array( "Options"                      , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Lotteries");
		
		uasort($this->ipsclass->cache['ibm_lottery'],array($this,'order_end_time'));
		
		if(is_array($this->ipsclass->cache['ibm_lottery']) and count($this->ipsclass->cache['ibm_lottery']))
		{
			foreach($this->ipsclass->cache['ibm_lottery'] as $lottery)
			{
				$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																					"<b>".$lottery['l_name']."</b><br />".$lottery['l_description'],
																					"Status: ".$trans[$lottery['l_status']]."<br />Tickets: ".($lottery['stock_tickets'] < 0 ? "Infinite" : $this->ipsclass->do_number_format($lottery['stock_tickets'])),
																					"Starting: ".$this->ipsclass->get_date($lottery['start_time'],'LONG')."<br />Ending: ".$this->ipsclass->get_date($lottery['end_time'],'LONG'),
																					"<img id=\"menu_{$lottery['l_id']}\" src='{$this->ipsclass->vars['board_url']}/skin_acp/IPB2_Standard/images/filebrowser_action.gif' border='0' alt='Options' class='ipd' style='float:right'/>",
																			)	);
				
				$this->ipsclass->html .= "<script type=\"text/javascript\">
	menu_build_menu( \"menu_{$lottery['l_id']}\",
  new Array(
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&action=edit&lottery={$lottery['l_id']}'>Edit Lottery</a>\",
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&action=delete&lottery={$lottery['l_id']}'>Delete Lottery</a>\",
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&action=tickets&lottery={$lottery['l_id']}'>View Tickets</a>\"
      )     );
 </script>";
			}
		}
		else
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("No active lottery made yet",'center');
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$lottery = array();
		$lottery['l_id'] = 0;
		$lottery['l_name'] = "New Lottery";
		$lottery['l_description'] = "";
		$lottery['l_status'] = 'open';
		$lottery['start_time'] = time();
		$lottery['end_time'] = time() + 604800;
		$lottery['continuous'] = 1;
		$lottery['l_price'] = 10;
		$lottery['stock_tickets'] = -1;
		$lottery['sell_back'] = 2;
		$lottery['create_time'] = time();
		$lottery['max_tickets'] = 0;
		$this->_acp_lottery_form($lottery);
		
		$this->ipsclass->admin->output();
	}
	
	function acp_type_lottery()
	{
		if($this->ipsclass->input['l_id'] != 0)
		{
			if(!is_array($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['l_id']]))
			{
				$this->ipsclass->admin->error("Cannot find lottery");
			}
			if($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['l_id']]['l_status'] == 'drawn')
			{
				$this->ipsclass->admin->error("The lottery has already been drawn");
			}
			$this->ipsclass->input['l_type'] = $this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['l_id']]['l_type'];
		}
		$file = $this->ipsclass->input['l_type'];
		require_once(ROOT_PATH."sources/market/lottery/".$file);
		$class = $this->ipsclass->market_class->get_class_name($file);
		$l_type = new $class;
		$l_type->ipsclass =& $this->ipsclass;
		$l_type->_load($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['l_id']]);
		
		$lottery['l_id'] = $this->ipsclass->input['l_id'];
		$lottery['l_name'] = $this->ipsclass->input['l_name'];
		$lottery['l_description'] = $_POST['l_description'];
		$lottery['l_status'] = $this->ipsclass->input['l_status'];
		$lottery['l_type'] = $this->ipsclass->input['l_type'];
		$lottery['start_time'] = $this->ipsclass->input['start_time'];
		$lottery['end_time'] = $this->ipsclass->input['end_time'];
		$lottery['continuous'] = $this->ipsclass->input['continuous'];
		$lottery['l_price'] = $this->ipsclass->input['l_price'];
		$lottery['stock_tickets'] = $this->ipsclass->input['stock_tickets'];
		$lottery['sell_back'] = $this->ipsclass->input['sell_back'];
		$lottery['create_time'] = $this->ipsclass->input['create_time'];
		$lottery['max_tickets'] = $this->ipsclass->input['max_tickets'];
		
		$html = $l_type->admin_form();
		
		if(!$html)
		{
			$this->acp_form_lottery();
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row("<b>".$l_type->name."</b><br />".$l_type->description,'left','tablerow1')."<br />";
		
		$this->ipsclass->html .= $this->_acp_start_form(array(
																	array('action','form'),
														),'theAdminForm',"onsubmit='return ValidateForm()'");
		
		$hidden = array();
		foreach($lottery as $k => $v)
		{
			$hidden[] = array($k,$v);
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->form_hidden($hidden);
		
		
		$this->ipsclass->html .= $html;
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form_standalone("Edit prizes");
		
		$this->ipsclass->admin->output();
	}
	
	function acp_form_lottery()
	{
		$file = $this->ipsclass->input['l_type'];
		require_once(ROOT_PATH."sources/market/lottery/".$file);
		$class = $this->ipsclass->market_class->get_class_name($file);
		$l_type = new $class;
		$l_type->ipsclass =& $this->ipsclass;
		$l_type->_load($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['l_id']]);
		
		$prizes = $l_type->prizes_types(1);
		
		$lottery = array();
		$lottery['l_id'] = $this->ipsclass->input['l_id'];
		$lottery['l_name'] = $this->ipsclass->input['l_name'];
		$lottery['l_description'] = $_POST['l_description'];
		$lottery['l_status'] = $this->ipsclass->input['l_status'];
		$lottery['l_type'] = $this->ipsclass->input['l_type'];
		$lottery['start_time'] = $this->ipsclass->input['start_time'];
		$lottery['end_time'] = $this->ipsclass->input['end_time'];
		$lottery['continuous'] = $this->ipsclass->input['continuous'];
		$lottery['l_price'] = $this->ipsclass->input['l_price'];
		$lottery['stock_tickets'] = $this->ipsclass->input['stock_tickets'];
		$lottery['sell_back'] = $this->ipsclass->input['sell_back'];
		$lottery['create_time'] = $this->ipsclass->input['create_time'];
		$lottery['max_tickets'] = $this->ipsclass->input['max_tickets'];
		$l_type->admin_save('hidden',$lottery);
		
		$this->ipsclass->html .= $this->_acp_start_form(array(
																	array('action','save'),
														),'theAdminForm',"onsubmit='return ValidateForm()'");
		
		$hidden = array();
		foreach($lottery as $k => $v)
		{
			$hidden[] = array($k,$v);
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->form_hidden($hidden);
		
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "40%" );
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "60%" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Set prizes");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("<b>".$l_type->name."</b><br />".$l_type->description, 'left', 'tablerow1');
		
		foreach($prizes as $k => $p)
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic($p['display'], 'left', 'tablesubheader');
			
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>".$this->ipsclass->vars['market_currency']." Prize for matching ".$p['matching']."</b><br />Chances of winning this: ".$p['chances'],
																				  $this->ipsclass->numbers->currency_format($this->ipsclass->adskin->form_simple_input("prizes[money][".$k."]",$this->ipsclass->input['l_id'] == 0 ? 0 : $this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['l_id']]['prizes']['money'][$k]))
																		 )      );
																		 
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Item Prizes for matching ".$p['matching']."</b><br />Chances of winning this: ".$p['chances'],
																				  $this->ipsclass->market_admin->compile_item_list("prizes[items][".$k."]",$this->ipsclass->input['l_id'] == 0 ? array() : $this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['l_id']]['prizes']['items'][$k],'item_table_'.$k,'item_id_'.$k,'quan_id_'.$k)
																		 )      );
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form("Add prizes");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->admin->output();
	}
	
	function acp_edit_lottery()
	{
		$this->ipsclass->input['lottery'] = intval($this->ipsclass->input['lottery']);
		if(!is_array($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]))
		{
			$this->ipsclass->admin->error("Cannot find lottery");
		}
		if($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['l_status'] == 'drawn')
		{
			$this->ipsclass->admin->error("The lottery has already been drawn");
		}
		
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=starter', 'Manage Lotteries' );
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=starter&amp;action=edit&amp;lottery='.$this->ipsclass->input['l_id'], 'Edit Lottery Information' );
		
		$this->_acp_lottery_form($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]);
		
		$this->ipsclass->admin->output();
	}
	
	function _acp_lottery_form($lottery = array())
	{
		$files = $this->ipsclass->market_class->get_file_list(ROOT_PATH."sources/market/lottery",0);
		$drop_down = array();
		foreach($files as $type)
		{
			if(strstr($type,"lottery_") != $type || substr($type,-4) != '.php')
			{
				continue;
			}
			
			$class_name = $this->ipsclass->market_class->get_class_name($type);
			
			require_once(ROOT_PATH."sources/market/lottery/".$type);
			$l_type = new $class_name;
			
			if(is_subclass_of($l_type,'lottery_template'))
			{
				$drop_down[] = array($type,$l_type->name);
			}
		}
		
		$date = $this->ipsclass->unixstamp_to_human($lottery['start_time']);
		$start = sprintf("%02d/%02d/%04d %02d:%02d", $date['month'], $date['day'], $date['year'], $date['hour'] , $date['minute'] );
		$date = $this->ipsclass->unixstamp_to_human($lottery['end_time']);
		$end = sprintf("%02d/%02d/%04d %02d:%02d", $date['month'], $date['day'], $date['year'], $date['hour'] , $date['minute'] );
		
		if ( $this->ipsclass->han_editor->method == 'rte' )
		{
			$lottery['l_description'] = $this->ipsclass->parser->pre_display_parse( $this->ipsclass->parser->pre_db_parse( $lottery['l_description'] ) );
			$lottery['l_description'] = $this->ipsclass->parser->convert_ipb_html_to_html( $lottery['l_description'] );
		}
		else
		{
			$lottery['l_description'] = $this->ipsclass->parser->pre_edit_parse( $lottery['l_description'] );
		}
        
		$this->ipsclass->html .= $this->_acp_start_form(array(
																	array('action','type'),
														),'theAdminForm',"onsubmit='return ValidateForm()'");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->form_hidden(array(array('l_id',$lottery['l_id'])));
		
		if($lottery['l_id'])
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->form_hidden(array(array('create_time',time()-time()%60)));
		}
		
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "40%" );
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "60%" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table($lottery['l_id'] ? "Edit a Lottery" : "Add a Lottery");
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Name</b><br />The name of the lottery.",
																			  $this->ipsclass->adskin->form_input("l_name",$lottery['l_name'])
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("<b>Description</b>: The description for the quiz.<br />".$this->ipsclass->han_editor->show_editor( $lottery['l_description'], 'l_description' ), 'left', 'tablerow1');
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Status of the lottery</b><br />When the lottery is closed, no one can buy tickets but it still will be drawn at end time.",
																			  $this->ipsclass->adskin->form_dropdown("l_status",array(array('open',"Open"),array('closed',"Closed")),$lottery['l_status'])
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Lottery Type</b><br />A loose lottery is a lottery could match any amount of numbers. An exact lottery is a lottery that have to have all the numbers.",
																			  $this->ipsclass->adskin->form_dropdown("l_type",$drop_down,$lottery['l_type'],$lottery['l_id'] == 0 ? '' : "disabled='disabled'")
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Starting time of this lottery</b><br />Input Format (24-hour time): MM/DD/YYYY HH:MM<br /><i>The lottery is automatically closed until the starting time.</i>",
																			  $this->ipsclass->adskin->form_input("start_time",$start)
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Ending time of this lottery</b><br />Input Format (24-hour time): MM/DD/YYYY HH:MM<br /><i>The lottery is automatically closed until the starting time.</i>",
																			  $this->ipsclass->adskin->form_input("end_time",$end)
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Is this lottery continuous?</b>",
																			  $this->ipsclass->adskin->form_dropdown("continuous",array(array(0,"Not continueous"),array(1,"Consecutively Continuous"),array(2,"Continuous with delay")),$lottery['continuous'])
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Ticket Price</b>",
																			  $this->ipsclass->numbers->currency_format($this->ipsclass->adskin->form_simple_input("l_price",$lottery['l_price']))
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Ticket Stock</b><br />Input -1 for infinite tickets",
																			  $this->ipsclass->adskin->form_simple_input("stock_tickets",$lottery['stock_tickets'])." tickets"
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Maximum tickets someone can hold</b><br />0 for unlimited",
																			  $this->ipsclass->adskin->form_simple_input("max_tickets",$lottery['max_tickets'])
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Allow sell tickets back</b><br />This will refund the user's money back",
																			  $this->ipsclass->adskin->form_dropdown("sell_back",array(array(0,"No Sell Back"),array(1,"Sell ticket back, not add ticket back to stock"),array(2,"Sell ticket back, add ticket back to stock")),$lottery['sell_back'])
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form("Edit Settings");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
	}
	
	function acp_save_lottery()
	{
		$this->ipsclass->input['l_id'] = intval($this->ipsclass->input['l_id']);
		if($this->ipsclass->input['l_id'] != 0 && !is_array($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['l_id']]))
		{
			$this->ipsclass->admin->error("Cannot find lottery");
		}
		
		$file = $this->ipsclass->input['l_type'];
		require_once(ROOT_PATH."sources/market/lottery/".$file);
		$class = $this->ipsclass->market_class->get_class_name($file);
		$l_type = new $class;
		$l_type->ipsclass =& $this->ipsclass;
		$l_type->_load($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['l_id']]);
		
		$prizes = $l_type->prizes_types(1);
		
		list($date, $time) = explode(" ",$this->ipsclass->input['start_time']);
		list($month,$day,$year) = explode("/",$date);
		list($hour,$minute) = explode(":",$time);
		if($this->ipsclass->market_class->check_24_time($month, $day, $year, $hour, $minute))
		{
			$this->ipsclass->input['start_time'] = $this->ipsclass->convert_local_date_to_unix( array( 'month'  => intval($month),
																									   'day'    => intval($day),
																									   'year'   => intval($year),
																									   'hour'   => intval($hour),
																									   'minute' => intval($minute) ) );
		}
		else
		{
			$this->ipsclass->admin->error("Bad starting time, the date/time must be in correct format and a valid date/time");
		}
		list($date, $time) = explode(" ",$this->ipsclass->input['end_time']);
		list($month,$day,$year) = explode("/",$date);
		list($hour,$minute) = explode(":",$time);
		if($this->ipsclass->market_class->check_24_time($month, $day, $year, $hour, $minute))
		{
			$this->ipsclass->input['end_time'] = $this->ipsclass->convert_local_date_to_unix( array( 'month'  => intval($month),
																									 'day'    => intval($day),
																									 'year'   => intval($year),
																									 'hour'   => intval($hour),
																									 'minute' => intval($minute) ) );
		}
		else
		{
			$this->ipsclass->admin->error("Bad ending time, the date/time must be in correct format and a valid date/time");
		}
		
		foreach(array_keys($prizes) as $k)
		{
			$this->ipsclass->input['prizes']['money'][$k] = $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['prizes']['money'][$k],'int');
			$this->ipsclass->input['prizes']['items'][$k] = $this->ipsclass->market_admin->parse_input_item_list(array('prizes','items',$k));
		}
		
		$lottery = array();
		$lottery['l_name'] = $this->ipsclass->input['l_name'];
		$lottery['l_description'] = $this->ipsclass->parser->pre_display_parse( $this->ipsclass->parser->pre_db_parse( $this->ipsclass->han_editor->process_raw_post( 'l_description' ) ) );
		$lottery['l_status'] = $this->ipsclass->input['l_status'];
		$lottery['start_time'] = $this->ipsclass->input['start_time'];
		$lottery['end_time'] = $this->ipsclass->input['end_time'];
		$lottery['continuous'] = min(max($this->ipsclass->input['continuous'],0),2);
		$lottery['l_price'] = $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['l_price'],'int');
		$lottery['stock_tickets'] = intval($this->ipsclass->input['stock_tickets']);
		$lottery['max_tickets'] = intval($this->ipsclass->input['max_tickets']);
		$lottery['sell_back'] = min(max($this->ipsclass->input['sell_back'],0),2);
		$lottery['prizes'] = serialize($this->ipsclass->input['prizes']);
		
		$l_type->admin_save('save',$lottery);
		
		if($this->ipsclass->input['l_id'] == 0)
		{
			$lottery['l_type'] = $this->ipsclass->input['l_type'];
			$lottery['create_time'] = $this->ipsclass->input['create_time'] ? $this->ipsclass->input['create_time'] : max(time(),$this->ipsclass->input['start_time']);
			
			$this->ipsclass->DB->do_insert('market_lottery',$lottery);
		
			$this->ipsclass->admin->save_log("ibMarket: Lottery Added(".$this->ipsclass->input['l_name'].")");
		}
		else
		{
			$this->ipsclass->DB->do_update('market_lottery',$lottery,"l_id=".$this->ipsclass->input['l_id']);
			
			$this->ipsclass->admin->save_log("ibMarket: Lottery Editted(".$this->ipsclass->input['l_name'].")");
		}
		
		$this->lottery_cache();
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js,"Lottery, ".$this->ipsclass->input['l_name'].", saved...");
	}
	
	function acp_delete_lottery()
	{
		$this->ipsclass->input['lottery'] = intval($this->ipsclass->input['lottery']);
		if(!is_array($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]))
		{
			$this->ipsclass->admin->error("Cannot find lottery");
		}
		
		$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_lottery','where'=>"l_id=".$this->ipsclass->input['lottery']));
		$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_lottery_tickets','where'=>"lottery_id=".$this->ipsclass->input['lottery']));
		
		$this->ipsclass->admin->save_log("ibMarket: Lottery Deleted(".$this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['l_name'].")");
		
		$this->lottery_cache();
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js,"Lottery deleted...");
	}
	
	function acp_view_tickets()
	{
		$this->ipsclass->input['lottery'] = intval($this->ipsclass->input['lottery']);
		if(!is_array($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]))
		{
			$this->ipsclass->admin->error("Cannot find lottery");
		}
		
		$LIMIT = 25;
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		
		$count = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as count','from'=>'market_lottery_tickets','where'=>"lottery_id=".$this->ipsclass->input['lottery']));
		$page = $this->ipsclass->adskin->build_pagelinks(	array(	'TOTAL_POSS'   => $count['count'],
																	'PER_PAGE'     => $LIMIT,
																	'USE_ST'       => 'st',
																	'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																	'L_SINGLE'     => "Single Page",
																	'BASE_URL'     => $this->ipsclass->base_url."&amp;".$this->ipsclass->form_code."&amp;action=ticket&amp;lottery=".$this->ipsclass->input['lottery']
															)	);

		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=list', 'Manage Lotteries' );
		$this->ipsclass->admin->nav[] 		= array( ''                                           , 'View Tickets' );
		$this->ipsclass->admin->nav[] 		= array( ''                                           , $this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['l_name'] );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->html .= "<br />";
		
		$this->ipsclass->adskin->td_header[] = array( "Member"        , "" );
		$this->ipsclass->adskin->td_header[] = array( "Date Bought"   , "" );
		$this->ipsclass->adskin->td_header[] = array( "Ticket Number" , "" );
		$this->ipsclass->adskin->td_header[] = array( "IP Address"    , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Tickets");
		
		$this->ipsclass->DB->build_query(array(
												'select' => 't.*',
												'from' => array('market_lottery_tickets'=>'t'),
												'add_join' => array(
																		array(
																				'select' => 'm.members_display_name',
																				'from' => array('members'=>'m'),
																				'where' => 'm.id=t.member_id',
																				'type' => 'left',
																			),
																	),
												'where' => "lottery_id=".$this->ipsclass->input['lottery'],
												'order' => 't.time_bought DESC',
												'limit' => array($this->ipsclass->input['st'],$LIMIT),
										)	);
		$this->ipsclass->DB->exec_query();
		while($ticket = $this->ipsclass->DB->fetch_row())
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																				$ticket['members_display_name'],
																				$this->ipsclass->get_date($ticket['time_bought'],'LONG'),
																				$this->types[$ticket['lottery_id']]->display_numbers(unserialize($ticket['numbers_chosen'])),
																				$ticket['ip_address'],
																		)	);
		}
		
		if($this->ipsclass->DB->get_num_rows() == 0)
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("No tickets bought yet",'center');
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->admin->output();
	}
	
	function acp_old_lottery()
	{
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		$LIMIT = 25;
		
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=previous', 'Previous Lotteries' );
		
		$count = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as count','from'=>'market_lottery','where'=>"l_status='drawn'"));
		$page = $this->ipsclass->adskin->build_pagelinks(	array(	'TOTAL_POSS'   => $count['count'],
																	'PER_PAGE'     => $LIMIT,
																	'USE_ST'       => 'st',
																	'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																	'L_SINGLE'     => "Single Page",
																	'BASE_URL'     => $this->ipsclass->base_url."&amp;".$this->ipsclass->form_code."&amp;action=previous"
															)	);

		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->html .= "<br />";
		
		$this->ipsclass->adskin->td_header[] = array( "Name/Description" , "" );
		$this->ipsclass->adskin->td_header[] = array( "Type/Ended"       , "" );
		$this->ipsclass->adskin->td_header[] = array( "Options"          , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Lotteries");
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_lottery','where'=>"l_status='drawn'",'limit'=>array($this->ipsclass->input['st'],$LIMIT)));
		$this->ipsclass->DB->exec_query();
		while($lottery = $this->ipsclass->DB->fetch_row())
		{
			require_once(ROOT_PATH."sources/market/lottery/".$lottery['l_type']);
			$class = $this->ipsclass->market_class->get_class_name($lottery['l_type']);
			$type = new $class;
			
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																				"<b>".$lottery['l_name']."</b><br />".$lottery['l_description'],
																				"Type: ".$type->name."<br />Ending: ".$this->ipsclass->get_date($lottery['end_time'],'LONG'),
																				"<img id=\"menu_{$lottery['l_id']}\" src='{$this->ipsclass->vars['board_url']}/skin_acp/IPB2_Standard/images/filebrowser_action.gif' border='0' alt='Options' class='ipd' style='float:right'/>",
																		)	);
			
			$this->ipsclass->html .= "<script type=\"text/javascript\">
	menu_build_menu( \"menu_{$lottery['l_id']}\",
  new Array(
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&action=result&lottery={$lottery['l_id']}'>View Tickets</a>\"
      )     );
</script>";
		}
		
		if($this->ipsclass->DB->get_num_rows() == 0)
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("No active lottery made yet",'center');
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->admin->output();
	}
	
	function acp_view_result()
	{
		$this->ipsclass->input['lottery'] = intval($this->ipsclass->input['lottery']);
		$lottery = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_lottery','where'=>"l_id=".$this->ipsclass->input['lottery']));
		$lottery['prizes'] = unserialize($lottery['prizes']);
		if(!$lottery)
		{
			$this->ipsclass->admin->error("Cannot find lottery");
		}
		require_once(ROOT_PATH."sources/market/lottery/".$lottery['l_type']);
		
		$class = $this->ipsclass->market_class->get_class_name($lottery['l_type']);
		$type = new $class;
		$type->ipsclass =& $this->ipsclass;
		$type->_load($lottery);
		$winnables = $type->prizes_types();
		
		$LIMIT = 25;
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		
		$count = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as count','from'=>'market_lottery_tickets','where'=>"lottery_id=".$this->ipsclass->input['lottery']));
		$page = $this->ipsclass->adskin->build_pagelinks(	array(	'TOTAL_POSS'   => $count['count'],
																	'PER_PAGE'     => $LIMIT,
																	'USE_ST'       => 'st',
																	'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																	'L_SINGLE'     => "Single Page",
																	'BASE_URL'     => $this->ipsclass->base_url."&amp;".$this->ipsclass->form_code."&amp;action=ticket&amp;lottery=".$this->ipsclass->input['lottery']
															)	);

		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=list', 'Manage Lotteries' );
		$this->ipsclass->admin->nav[] 		= array( ''                                           , 'View Tickets'     );
		$this->ipsclass->admin->nav[] 		= array( ''                                           , $lottery['l_name'] );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->html .= "<br />";
		
		$this->ipsclass->adskin->td_header[] = array( "Member"        , "" );
		$this->ipsclass->adskin->td_header[] = array( "Date Bought"   , "" );
		$this->ipsclass->adskin->td_header[] = array( "Ticket Number" , "" );
		$this->ipsclass->adskin->td_header[] = array( "IP Address"    , "" );
		$this->ipsclass->adskin->td_header[] = array( "Prize Won"     , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Tickets");
		
		$this->ipsclass->DB->build_query(array(
												'select' => 't.*',
												'from' => array('market_lottery_tickets'=>'t'),
												'add_join' => array(
																		array(
																				'select' => 'm.members_display_name',
																				'from' => array('members'=>'m'),
																				'where' => 'm.id=t.member_id',
																				'type' => 'left',
																			),
																	),
												'where' => "lottery_id=".$this->ipsclass->input['lottery'],
												'order' => 't.time_bought DESC',
												'limit' => array($this->ipsclass->input['st'],$LIMIT),
										)	);
		$this->ipsclass->DB->exec_query();
		while($ticket = $this->ipsclass->DB->fetch_row())
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																				$ticket['members_display_name'],
																				$this->ipsclass->get_date($ticket['time_bought'],'LONG'),
																				$type->display_numbers(unserialize($ticket['numbers_chosen'])),
																				$ticket['ip_address'],
																				$ticket['t_correct'] ? $winnables[$ticket['t_correct']]['display'] : "- NONE -",
																		)	);
		}
		
		if($this->ipsclass->DB->get_num_rows() == 0)
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("No tickets bought yet",'center');
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->admin->output();
	}
	
	function acp_install()
	{
		$this->ipsclass->DB->load_cache_file(ROOT_PATH.'sources/market/sql/'.$this->ipsclass->vars['sql_driver'].'_plugin_queries.php','sql_plugin_queries');
		
		$this->ipsclass->DB->build_query_from_cache('table_lottery',array(),'sql_plugin_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_lottery_tickets',array(),'sql_plugin_queries');
		$this->ipsclass->DB->exec_query();
	}
	
	function acp_uninstall()
	{
		$this->ipsclass->DB->sql_drop_table( 'market_lottery' );
		$this->ipsclass->DB->sql_drop_table( 'market_lottery_tickets' );
	}
	
	function run()
	{
		$this->ipsclass->load_template('skin_market_plugin');
		$this->ipsclass->load_language('lang_market_plugin');
		
		$this->ipsclass->market_class->title[] = array($this->plugin['name'],'market_'.$this->plugin['link']);
		if(in_array($this->ipsclass->member['mgroup'],$this->plugin['use_permission']))
		{
			$this->ipsclass->market_class->menu[] = array(
															"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->ipsclass->lang['lottery_open_lottery']."</a></b>",
															"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=drawn'>".$this->ipsclass->lang['lottery_prev_lottery']."</a></b>",
															"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=manage'>".$this->ipsclass->lang['lottery_check_tickets']."</a></b>",
															"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=check'>".$this->ipsclass->lang['lottery_old_tickets']."</a></b>",
														);
			
			$do_redirect = array(
									'list' => 'list_lotteries',
									'ticket' => 'ticket_form',
									'buy' => 'buy_ticket',
									'prize' => 'view_prizes',
									'manage' => 'manage_tickets',
									'check' => 'check_tickets',
									'sell' => 'sell_back_ticket',
									'drawn' => 'drawn_lotteries',
								  );
			
			if(!isset($do_redirect[$this->ipsclass->input['do']]))
			{
				$this->ipsclass->input['do'] = 'list';
			}
		}
		else
		{
			$this->ipsclass->market_class->menu[] = array(
															"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->ipsclass->lang['lottery_open_lottery']."</a></b>",
															"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=drawn'>".$this->ipsclass->lang['lottery_prev_lottery']."</a></b>",
														);
			
			$do_redirect = array(
									'list' => 'list_lotteries',
									'prize' => 'view_prizes',
									'drawn' => 'drawn_lotteries',
								  );
			
			if(!isset($do_redirect[$this->ipsclass->input['do']]))
			{
				$this->ipsclass->input['do'] = 'list';
			}
		}
		
		$func = 'run_'.$do_redirect[$this->ipsclass->input['do']];
		$this->$func();
	}
	
	function run_list_lotteries()
	{
		$this->ipsclass->subtitle = $this->ipsclass->lang['lottery_open_lottery'];
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->plugin['name']."</a>","<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->ipsclass->lang['lottery_open_lottery']."</a>");
		
		$lotteries = array();
		foreach($this->ipsclass->cache['ibm_lottery'] as $lottery)
		{
			$lottery['tickets'] = $lottery['stock_tickets'] < 0 ? $this->ipsclass->lang['infinite'] : $this->ipsclass->numbers->do_number_format($lottery['stock_tickets']);
			$lottery['drawing'] = $this->ipsclass->get_date($lottery['end_time'],'LONG');
			$lottery['price'] = $this->ipsclass->numbers->format_currency($lottery['l_price']);
			$lottery['type'] = $this->types[$lottery['l_id']]->name;
			
			$lotteries[] = $lottery;
		}
		
		usort($lotteries,array(&$this,'order_end_time'));
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->lottery_main_page($lotteries);
	}
	
	function order_end_time($a,$b)
	{
		return $a['end_time'] < $b['end_time'] ? -1 : ($a['end_time'] > $b['end_time'] ? 1 : 0);
	}
	
	function run_ticket_form()
	{
		if(!is_array($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]) || $this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['l_status'] == 'closed')
		{
			$this->ipsclass->boink_it($this->ipsclass->market_class->base_url."plugin=".$this->plugin['link']);
		}
		
		if($this->ipsclass->numbers->compare($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['stock_tickets'],0) == 0 )
		{
			$this->ipsclass->Error(array('MSG'=>'lottery_no_tickets_left'));
		}
		
		$form = $this->types[$this->ipsclass->input['lottery']]->create_numbers();
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->lottery_buy_ticket($form);
	}
	
	function run_buy_ticket()
	{
		if(!is_array($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]) || $this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['l_status'] == 'closed')
		{
			$this->ipsclass->boink_it($this->ipsclass->market_class->base_url."plugin=".$this->plugin['link']);
		}
		
		if($this->ipsclass->numbers->compare($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['l_price']) < 0)
		{
			$this->ipsclass->Error(array('MSG'=>'lottery_not_enough_money'));
		}
		
		if($this->ipsclass->numbers->compare($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['stock_tickets'],0) == 0)
		{
			$this->ipsclass->Error(array('MSG'=>'lottery_no_tickets_left'));
		}
		
		if($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['max_tickets'])
		{
			$count = $this->ipsclass->DB->build_and_execy_query(array('select'=>'COUNT(*) as count','from'=>'market_lottery_tickets','where'=>"member_id=".$this->ipsclass->member['id']." AND lottery_id=".$this->ipsclass->input['lottery']));
			if($this->ipsclass->numbers->compare($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['max_tickets'],$count) <= 0)
			{
				$this->ipsclass->Error(array('MSG'=>'lottery_too_many_tickets'));
			}
		}
		
		if(!is_array($this->ipsclass->input['nums']))
		{
			$this->ipsclass->Error(array('MSG'=>'lottery_invalid_numbers'));
		}
		
		$nums = array();
		$allowed = $this->types[$this->ipsclass->input['lottery']]->create_numbers();
		foreach($this->ipsclass->input['nums'] as $set => $picked)
		{
			if(!is_array($allowed[$set]))
			{
				continue;
			}
			if(count($picked) != $allowed[$set]['max_pick'])
			{
				$this->ipsclass->Error(array('MSG'=>'lottery_invalid_numbers'));
			}
			$nums[$set] = array();
			foreach(array_keys($picked) as $k)
			{
				if(!isset($allowed[$set]['numbers'][$k]))
				{
					$this->ipsclass->Error(array('MSG'=>'lottery_invalid_numbers'));
				}
				$nums[$set][$k] = $allowed[$set]['numbers'][$k];
			}
		}
		
		$ticket = array(
							'member_id' => $this->ipsclass->member['id'],
							'lottery_id' => $this->ipsclass->input['lottery'],
							'price_bought' => $this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['l_price'],
							'time_bought' => time(),
							'numbers_chosen' => $nums,
							'checked' => 0,
							't_correct' => '',
							'ip_address' => $this->ipsclass->ip_address,
						);
		
		$this->types[$this->ipsclass->input['lottery']]->create_ticket($ticket);
		
		$ticket['numbers_chosen'] = serialize($ticket['numbers_chosen']);
		
		$this->ipsclass->DB->do_insert('market_lottery_tickets',$ticket);
		$this->ipsclass->DB->do_update('members',array(
														$this->ipsclass->vars['market_members_field'] => $this->ipsclass->numbers->subtract($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['l_price']),
				),"id=".$this->ipsclass->member['id']);
		if($this->ipsclass->numbers->compare($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['stock_tickets'],0) > 0)
		{
			$this->ipsclass->DB->do_update('market_lottery',array(
																		'stock_tickets' => $this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['stock_tickets']-1,
						),"l_id=".$this->ipsclass->input['lottery']);
			$this->lottery_cache();
		}
		
		$this->ipsclass->market_class->redirect('lottery_ticket_bought',"plugin=".$this->ipsclass->input['plugin']);
	}
	
	function run_manage_tickets()
	{
		$this->ipsclass->subtitle = $this->ipsclass->lang['lottery_manage_tickets'];
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->plugin['name']."</a>","<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=manage'>".$this->ipsclass->lang['lottery_manage_tickets']."</a>");
		
		$tickets = array();
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_lottery_tickets','where'=>"checked=0 AND member_id=".$this->ipsclass->member['id']));
		$this->ipsclass->DB->exec_query();
		while($ticket = $this->ipsclass->DB->fetch_row())
		{
			$ticket['time_bought'] = $this->ipsclass->get_date($ticket['time_bought'],'LONG');
			$ticket['numbers'] = $this->types[$ticket['lottery_id']]->display_numbers(unserialize($ticket['numbers_chosen']));
			$tickets[] = $ticket;
		}
		foreach($this->ipsclass->cache['ibm_lottery'] as $l_id => $lottery)
		{
			$this->ipsclass->cache['ibm_lottery'][$l_id]['drawing'] = $this->ipsclass->get_date($lottery['end_time'],'LONG');
		}
		
		usort($tickets,array(&$this,'order_active_tickets'));
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->lottery_manage_tickets($tickets);
	}
	
	function order_active_tickets($a,$b)
	{
		if($a['lottery_id'] == $b['lottery_id'])
		{
			if($a['time_bought'] < $b['time_bought'])
			{
				return -1;
			}
			else
			{
				return 1;
			}
		}
		else
		{
			if($this->ipsclass->cache['ibm_lottery'][$a['lottery_id']]['end_time'] == $this->ipsclass->cache['ibm_lottery'][$b['lottery_id']]['end_time'])
			{
				if($a['lottery_id'] < $b['lottery_id'])
				{
					return -1;
				}
				else
				{
					return 1;
				}
			}
			elseif($this->ipsclass->cache['ibm_lottery'][$a['lottery_id']]['end_time'] < $this->ipsclass->cache['ibm_lottery'][$b['lottery_id']]['end_time'])
			{
				return -1;
			}
			else
			{
				return 1;
			}
		}
	}
	
	function run_sell_back_ticket()
	{
		$this->ipsclass->input['ticket'] = intval($this->ipsclass->input['ticket']);
		
		$ticket = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_lottery_tickets','where'=>"t_id=".$this->ipsclass->input['ticket']));
		
		if(!$ticket || $this->ipsclass->input['lottery'] != $ticket['lottery_id'] || $this->ipsclass->member['id'] != $ticket['member_id'])
		{
			$this->ipsclass->Error(array('MSG'=>'lottery_invalid_ticket'));
		}
		
		if(!is_array($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]))
		{
			$this->ipsclass->boink_it($this->ipsclass->market_class->base_url."plugin=".$this->plugin['link']);
		}
		
		if($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['sell_back'] == 0 || $this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['l_status'] == 'drawn')
		{
			$this->ipsclass->Error(array('MSG'=>'lottery_cant_sell_back'));
		}
		
		$this->ipsclass->DB->do_update('members',array(
														$this->ipsclass->vars['market_members_field'] => $this->ipsclass->numbers->add($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$ticket['price_bought']),
				),"id=".$this->ipsclass->member['id']);
		if($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['sell_back'] == 2)
		{
			$this->ipsclass->DB->do_update('market_lottery',array(
																		'stock_tickets' => $this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['stock_tickets']+1,
						),"l_id=".$this->ipsclass->input['lottery']);
			$this->lottery_cache();
		}
		$this->ipsclass->DB->do_delete('market_lottery_tickets',"t_id=".$this->ipsclass->input['ticket']);
		
		$this->ipsclass->market_class->redirect('lottery_ticket_resold',"plugin=".$this->ipsclass->input['plugin']."&do=manage");
	}
	
	function run_check_tickets()
	{
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		
		foreach($this->ipsclass->cache['ibm_lottery'] as $l_id => $lottery)
		{
			$this->ipsclass->cache['ibm_lottery'][$l_id]['winnings'] = $this->types[$l_id]->prizes_types();
		}
		
		$this->ipsclass->subtitle = $this->ipsclass->lang['lottery_old_tickets'];
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->plugin['name']."</a>","<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=check'>".$this->ipsclass->lang['lottery_old_tickets']."</a>");
		
		$LIMIT = 25;
		$total = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as total','from'=>'market_lottery_tickets','where'=>"checked=1 AND member_id=".$this->ipsclass->member['id']));
		$page_links = $this->ipsclass->build_pagelinks(	array(	'TOTAL_POSS'   => $total['total'],
																'PER_PAGE'     => $LIMIT,
																'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																'L_SINGLE'     => $this->ipsclass->compiled_templates['skin_global']->pagination_compile($this->ipsclass->compiled_templates['skin_global']->pagination_make_jump(),"","",$this->ipsclass->compiled_templates['skin_global']->pagination_current_page(1),"","",1,$LIMIT,$this->ipsclass->market_class->base_url."plugin=".$this->ipsclass->input['plugin']."&amp;do=check",0,'st'),
																'BASE_URL'     => $this->ipsclass->market_class->base_url."plugin=".$this->ipsclass->input['plugin']."&amp;do=check",
																'USE_ST'       => 'st',
														)	);
		
		$get_lotteries = array();
		$tickets = array();
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_lottery_tickets','where'=>"checked=1 AND member_id=".$this->ipsclass->member['id'],'order'=>"lottery_id ASC, time_bought DESC",'limit'=>array($this->ipsclass->input['st'],$LIMIT)));
		$this->ipsclass->DB->exec_query();
		while($ticket = $this->ipsclass->DB->fetch_row())
		{
			$get_lotteries[$ticket['lottery_id']][] = $ticket['t_id'];
			$ticket['time_bought'] = $this->ipsclass->get_date($ticket['time_bought'],'LONG');
			$tickets[$ticket['t_id']] = $ticket;
		}
		
		if(count($get_lotteries))
		{
			$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_lottery','where'=>"l_id IN (".implode(", ",array_keys($get_lotteries)).")",'order'=>"l_id DESC"));
			$q = $this->ipsclass->DB->exec_query();
			while($lottery = $this->ipsclass->DB->fetch_row($q))
			{
				$lottery['prizes'] = unserialize($lottery['prizes']);
				require_once(ROOT_PATH."sources/market/lottery/".$lottery['l_type']);
				$class = $this->ipsclass->market_class->get_class_name($lottery['l_type']);
				$type = new $class;
				$type->ipsclass =& $this->ipsclass;
				$type->_load($lottery);
				
				$prizes = $type->prizes_types();
				$end_time = $this->ipsclass->get_date($lottery['end_time'],'LONG');
				
				foreach($get_lotteries[$lottery['l_id']] as $t_id)
				{
					$tickets[$t_id]['time_drawn'] = $end_time;
					$tickets[$t_id]['lottery'] = $lottery['l_name'];
					$tickets[$t_id]['lot_desc'] = $lottery['l_desc'];
					$tickets[$t_id]['numbers'] = $type->display_numbers(unserialize($tickets[$t_id]['numbers_chosen']));
					$tickets[$t_id]['won'] = $tickets[$t_id]['t_correct'] !== '' ? $prizes[$tickets[$t_id]['t_correct']]['display'] : $this->ipsclass->lang['lottery_no_win'];
				}
			}
		}
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->lottery_old_tickets($tickets,$page_links);
	}
	
	function run_view_prizes()
	{
		if(!is_array($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]))
		{
			$this->ipsclass->input['lottery'] = intval($this->ipsclass->input['lottery']);
			$this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']] = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_lottery','where'=>"l_id=".$this->ipsclass->input['lottery']));
			$this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['prizes'] = unserialize($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['prizes']);
			if(!$this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']])
			{
				$this->ipsclass->boink_it($this->ipsclass->market_class->base_url."plugin=".$this->plugin['link']);
			}
			require_once(ROOT_PATH."sources/market/lottery/".$this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['l_type']);
		}
		
		$class = $this->ipsclass->market_class->get_class_name($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['l_type']);
		$type = new $class;
		$type->ipsclass =& $this->ipsclass;
		$type->_load($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]);
		
		$this->ipsclass->subtitle = $this->ipsclass->lang['lottery_view_prizes'];
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->plugin['name']."</a>",$this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['l_name'],$this->ipsclass->lang['lottery_view_prizes']);
		
		$total = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as total','from'=>'market_lottery_tickets','where'=>"lottery_id=".$this->ipsclass->input['lottery']));
		
		$this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['drawing'] = $this->ipsclass->get_date($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['end_time'],'LONG');
		$this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['tickets'] = $this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['stock_tickets'] < 0 ? $this->ipsclass->lang['infinite'] : $this->ipsclass->numbers->do_number_format($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['stock_tickets']);
		$this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['total_tickets'] = $this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['stock_tickets'] < 0 ? $this->ipsclass->lang['infinite'] : $this->ipsclass->numbers->do_number_format($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['stock_tickets'] + $total['total']);
		$this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['sold'] = $this->ipsclass->numbers->do_number_format($total['total']);
		$this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['type'] = $type->name;
		$this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['price'] = $this->ipsclass->numbers->format_currency($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['l_price']);
		
		$prizes = $type->prizes_types();
		foreach($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['prizes']['items'] as $t => $prize)
		{
			$items = array();
			if(is_array($prize) && count($prize))
			{
				foreach($prize as $i_id => $quan)
				{
					if($quan == 1)
					{
						$items[] = $this->ipsclass->cache['market_items'][$i_id]['item_name'];
					}
					else
					{
						$items[] = $this->ipsclass->cache['market_items'][$i_id]['item_name'];
					}
				}
			}
			else
			{
				$items[] = $this->ipsclass->lang['none'];
			}
			
			$prizes[$t]['tickets'] = 0;
			
			$this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['prizes']['money'][$t] = $this->ipsclass->numbers->format_currency($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['prizes']['money'][$t]);
			$this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['prizes']['items'][$t] = implode(", ", $items);
		}
		
		if($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['l_status'] == 'drawn')
		{
			$this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['numbers'] = $type->display_numbers(unserialize($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['correct_numbers']));
			
			$this->ipsclass->DB->build_query(array('select'=>'COUNT(*) as tickets,t_correct','from'=>'market_lottery_tickets','where'=>"lottery_id=".$this->ipsclass->input['lottery']." AND t_correct != ''",'group'=>'t_correct'));
			$this->ipsclass->DB->exec_query();
			while($count = $this->ipsclass->DB->fetch_row())
			{
				$prizes[$count['t_correct']]['tickets'] = $this->ipsclass->numbers->do_number_format($count['tickets']);
			}
		}
		
		$tickets = array();
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_lottery_tickets','where'=>"member_id=".$this->ipsclass->member['id']." AND lottery_id=".$this->ipsclass->input['lottery'],'order'=>'time_bought DESC'));
		$this->ipsclass->DB->exec_query();
		while($ticket = $this->ipsclass->DB->fetch_row())
		{
			$ticket['time_bought'] = $this->ipsclass->get_date($ticket['time_bought'],'LONG');
			$ticket['numbers'] = $type->display_numbers(unserialize($ticket['numbers_chosen']));
			$tickets[] = $ticket;
		}
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->lottery_view_prizes($prizes,$tickets);
	}
	
	function run_drawn_lotteries()
	{
		$this->ipsclass->subtitle = $this->ipsclass->lang['lottery_prev_lottery'];
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->plugin['name']."</a>","<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&ampdo=drawn'>".$this->ipsclass->lang['lottery_prev_lottery']."</a>");
		
		$LIMIT = 25;
		$total = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as total','from'=>'market_lottery','where'=>"l_status='drawn'"));
		$page_links = $this->ipsclass->build_pagelinks(	array(	'TOTAL_POSS'   => $total['total'],
																'PER_PAGE'     => $LIMIT,
																'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																'L_SINGLE'     => $this->ipsclass->compiled_templates['skin_global']->pagination_compile($this->ipsclass->compiled_templates['skin_global']->pagination_make_jump(),"","",$this->ipsclass->compiled_templates['skin_global']->pagination_current_page(1),"","",1,$LIMIT,$this->ipsclass->market_class->base_url."plugin=".$this->ipsclass->input['plugin']."&amp;do=check",0,'st'),
																'BASE_URL'     => $this->ipsclass->market_class->base_url."plugin=".$this->ipsclass->input['plugin']."&amp;do=drawn",
																'USE_ST'       => 'st',
														)	);
		
		$lotteries = array();
		$this->ipsclass->DB->build_query(array(
												'select' => 'l.*',
												'from' => array('market_lottery'=>'l'),
												'add_join' => array(
																		array(
																				'select' => 'COUNT(t.t_id) as tickets',
																				'from' => array('market_lottery_tickets'=>'t'),
																				'where' => "l.l_id=t.lottery_id",
																				'type' => 'left',
																			),
																	),
												'where' => "l.l_status='drawn'",
												'group' => 'l.l_id',
												'order' => 'end_time DESC',
												'limit' => array($this->ipsclass->input['st'],$LIMIT),
										)	);
		$this->ipsclass->DB->exec_query();
		while($lottery = $this->ipsclass->DB->fetch_row())
		{
			$lottery['tickets'] = $this->ipsclass->numbers->do_number_format($lottery['tickets']);
			$lottery['drawing'] = $this->ipsclass->get_date($lottery['end_time'],'LONG');
			$lottery['price'] = $this->ipsclass->numbers->format_currency($lottery['l_price']);
			
			require_once(ROOT_PATH."sources/market/lottery/".$lottery['l_type']);
			$class = $this->ipsclass->market_class->get_class_name($lottery['l_type']);
			$type = new $class;
			$lottery['type'] = $type->name;
			
			$lotteries[] = $lottery;
		}
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->lottery_drawn_page($lotteries,$page_links);
	}
}
?>